package com.wwwarehouse.common.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.R;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.ConvertToPcParams;
import com.wwwarehouse.common.bean.PcImportUnifyBean;
import com.wwwarehouse.common.bean.PcImportUnifySuccessBean;
import com.wwwarehouse.common.bean.PushImportSucessBean;
import com.wwwarehouse.common.bean.response.CardDeskTaskResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.common.Common;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.eventbus_event.CardDeskEvent;
import com.wwwarehouse.common.eventbus_event.PushImportEvent;
import com.wwwarehouse.common.eventbus_event.StartImportEvent;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ApkTools;
import com.wwwarehouse.common.tools.rsa.StringUtils;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;

/**
 * Created by feng.gao on 2017/10/20.
 * 最新版手机转PC统一跳转页面
 */
@Route(path = Constant.CONVERT_PC_IMPORT_UNIFY_FRAGMENT)

public class PcImportUnifyFragment extends BaseFragment implements View.OnClickListener {
	private StateLayout mStateLayout;
	private ConvertToPcParams mConvertToPcParams;
	private String title;
	private RelativeLayout mContentRl; //内容布局
	private LinearLayout mUrlLayout; //生成短链接页面
	private LinearLayout mDurationTimeLayout; //计时页面
	private LinearLayout mSuccessLayout; //导入成功页面
	private PcImportUnifyBean bean; //页面展示需要的实体


	//	短连接页面的
	private TextView mWebAddressTv;
	private ImageView mWechatIv;
	private String mUrl;

	//  计时页面的
	private TextView mTimeTv;
	private TextView mUrlTv;
	private Timer timer;
	private TimerTask timerTask;
	private long cnt;
	private long mTimeCost;

	// 导入成功页面的
	private TextView mTvMessage;
	private TextView mTvMessageAddResource;
	private TextView mCountTv;

	//	标识跳转不同导入页
	private String mOpercationId = "";

	private String mRequestUrl = Constant.PC_IMPORT_UNIFY_METHOD;


	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		return inflater.inflate(R.layout.convert_to_pc_empty_fragment, container, false);
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initView(view);


	}

	private void initView(View view) {
		EventBus.getDefault().register(this);
		mStateLayout = (StateLayout) view.findViewById(R.id.gaofeng_sl_state);
		mContentRl = (RelativeLayout) view.findViewById(R.id.content_rl);
		mSuccessLayout = (LinearLayout) view.findViewById(R.id.success_layout);
		mUrlLayout = (LinearLayout) view.findViewById(R.id.url_layout);
		mDurationTimeLayout = (LinearLayout) view.findViewById(R.id.duration_time_layout);
		mTvMessage = $(R.id.tv_message);
		mCountTv = $(R.id.count_tv);
		mTvMessageAddResource = $(R.id.tv_message_addresource);
		mSuccessLayout.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				EventBus.getDefault().post(new CardDeskEvent("clear_back_stack"));
			}
		});
		//全部隐藏只留状态页
		mContentRl.setVisibility(View.INVISIBLE);
		mUrlLayout.setVisibility(View.INVISIBLE);
		mSuccessLayout.setVisibility(View.INVISIBLE);
		mDurationTimeLayout.setVisibility(View.INVISIBLE);
	}

	@Override
	public void setTitle() {
		if (peekFragment() instanceof PcImportUnifyFragment && StringUtils.isNoneNullString(title)) {
			mActivity.setTitle(title);
		}
	}

	@Override
	public void requestDatas() {
		if (getArguments() != null) {
			if (getArguments().getSerializable(Constant.KEY_CARD_DESK_TASK_DETAILS) != null) {
				CardDeskTaskResponseBean.TaskBean taskBean = (CardDeskTaskResponseBean.TaskBean) getArguments().getSerializable(Constant.KEY_CARD_DESK_TASK_DETAILS);
				if (taskBean != null) {
					Map<String, Object> map = new HashMap<>();
					map.put("businessUnitId", taskBean.getBelongBusiness());
					map.put("ownerBuId", taskBean.getBelongBusiness());
					map.put("operationType", taskBean.getTaskType());
					map.put("operationUkid", taskBean.getCardUkid());
					map.put("userId", sp.getValue(Constant.sp_User_Id));
					if (StringUtils.isNoneNullString(taskBean.getCardName())) {
						title = taskBean.getCardName();
						mActivity.setTitle(title);
					}
					if (StringUtils.isNoneNullString(taskBean.getCardUkid())) {
						mOpercationId = taskBean.getCardUkid();
					}
					mStateLayout.showProgressView(true);
//					根据不同的卡片类型请求不同的接口地址，没有特殊情况都请求默认的接口地址
					if (taskBean.getTaskType().equals("DELIVER_MANAGE")) {
						mRequestUrl = Constant.PC_IMPORT_UPLOAD_SHIPPING_INFORMATION;
					}
					NoHttpUtils.httpPost(mRequestUrl, map, new NoHttpUtils.OnResponseListener() {
						@Override
						public void onSucceed(CommonClass commonClass, int what) {
							if (commonClass != null && commonClass.getData() != null && commonClass.getCode() != null) {
								if (commonClass.getCode().equals("0")) {
									mContentRl.setVisibility(View.VISIBLE);
									bean = JSON.parseObject(commonClass.getData().toString(), PcImportUnifyBean.class);
									if (bean != null) {
										mStateLayout.showContentView();
										if (StringUtils.isNoneNullString(bean.getOperationUkid())) {
											mOpercationId = bean.getOperationUkid();
										}
										if (StringUtils.isNoneNullString(bean.getTaskStep())) {
											if (bean.getTaskStep().equals("N")) {
												//跳转到生成短链接的页面
												mUrlLayout.setVisibility(View.VISIBLE);
												mDurationTimeLayout.setVisibility(View.INVISIBLE);
												setUrlLayoutData();
											} else {
												//跳转到时间页面
												mUrlLayout.setVisibility(View.INVISIBLE);
												mSuccessLayout.setVisibility(View.INVISIBLE);
												mDurationTimeLayout.setVisibility(View.VISIBLE);
												mTimeCost = bean.getTimeCost();
												setDurationTimeData(mTimeCost , bean.getUrl());
											}
										}

									}
								} else {
									mStateLayout.showSystemView(commonClass.getMsg(), true);
									mStateLayout.setSystemListener(new View.OnClickListener() {
										@Override
										public void onClick(View v) {
											requestDatas();
										}
									});
								}

							} else {
								mStateLayout.showEmptyView(true);
								mStateLayout.setSystemListener(new View.OnClickListener() {
									@Override
									public void onClick(View v) {
										requestDatas();
									}
								});
							}

						}

						@Override
						public void onFailed(String result, int what) {
							mStateLayout.showSystemView(result, true);
							mStateLayout.setSystemListener(new View.OnClickListener() {
								@Override
								public void onClick(View v) {
									requestDatas();
								}
							});
						}

						@Override
						public void onFinish(int what) {

						}
					}, 1);
				} else {
					mStateLayout.showSystemView(true);
					mStateLayout.setSystemListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							requestDatas();
						}
					});
				}
			} else {
				mStateLayout.showSystemView(true);
				mStateLayout.setSystemListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						requestDatas();
					}
				});
			}
		}

	}

	private void setDurationTimeData(long mTimeCost , String url) {
		mTimeTv = (TextView) mDurationTimeLayout.findViewById(R.id.time_task_view);
		mUrlTv = (TextView) mDurationTimeLayout.findViewById(R.id.url_tv);
		mDurationTimeLayout.findViewById(R.id.btn_confirm).setOnClickListener(this);
		timer = new Timer();
		cnt = mTimeCost;
		startClick();
		if (StringUtils.isNoneNullString(url)) {
//			mUrlTv.setText(url);
		}
	}

	private void setUrlLayoutData() {
		mWebAddressTv = (TextView) mUrlLayout.findViewById(R.id.web_address_tv);
		mWechatIv = (ImageView) mUrlLayout.findViewById(R.id.share_wechat_iv);
		mUrlLayout.findViewById(R.id.share_qq_iv).setOnClickListener(this);
		mWechatIv.setOnClickListener(this);
		if (!ApkTools.isWeixinInstall(mActivity)) {
			mWechatIv.setVisibility(View.GONE);
		}
		if (bean != null && bean.getUrl() != null) {
			mUrl = bean.getUrl();
			mWebAddressTv.setText("操作网址：" + bean.getUrl());
		}

	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.share_qq_iv) {
			if (mUrl != null) {
				Common.getInstance().shareQQ(mActivity, mUrl, "", "", mUrl);
			}
		} else if (v.getId() == R.id.share_wechat_iv) {
			if (mUrl != null) {
				Common.getInstance().shareWeixinTextMoment(mActivity, mUrl);
			}
		} else if (v.getId() == R.id.btn_confirm) {
			EventBus.getDefault().post(new CardDeskEvent("clear_back_stack"));
		}
	}


	/**
	 * 接收推送消息，跳转到导入成功页面。
	 *
	 * @param pushImportEvent
	 */
	public void onEventMainThread(PushImportEvent pushImportEvent) {
		if (peekFragment() instanceof PcImportUnifyFragment) {
//				开始判断跳转不同的导入成功页面
			if (!TextUtils.isEmpty(pushImportEvent.getResult())) {
				mUrlLayout.setVisibility(View.INVISIBLE);
				mDurationTimeLayout.setVisibility(View.INVISIBLE);
				mSuccessLayout.setVisibility(View.VISIBLE);
				PcImportUnifySuccessBean realthingBean = JSON.parseObject(pushImportEvent.getResult(), PcImportUnifySuccessBean.class);
				if (realthingBean != null) {
					PcImportUnifySuccessBean.MsgBean msg = realthingBean.getMsg();
					if (msg != null) {
						if (StringUtils.isNoneNullString(msg.getPushImportCount())) {
							mCountTv.setText(StringUtils.getResourceStr(mActivity , R.string.push_import_count , msg.getPushImportCount()));
						}
					}
				}

			}
		}
	}

	/**
	 * 接收推送消息，跳转到计时页面。
	 *
	 * @param startImportEvent
	 */
	public void onEventMainThread(StartImportEvent startImportEvent) {
		if (peekFragment() instanceof PcImportUnifyFragment) {
			PushImportSucessBean sucessBean = JSON.parseObject(startImportEvent.getResult(), PushImportSucessBean.class);
				if (sucessBean != null && sucessBean.getMsg() != null) {
					if (mOpercationId.equals(sucessBean.getMsg().getOperationUkid())) {
						if (!TextUtils.isEmpty(sucessBean.getMsg().getTimeCost())) {
							if (mDurationTimeLayout.getVisibility() == View.INVISIBLE) {
								mUrlLayout.setVisibility(View.INVISIBLE);
								mSuccessLayout.setVisibility(View.INVISIBLE);
								mDurationTimeLayout.setVisibility(View.VISIBLE);
								mTimeCost = Long.valueOf(sucessBean.getMsg().getTimeCost());
								if (bean == null || StringUtils.isNullString(bean.getUrl())) {
									return;
								}
								setDurationTimeData(mTimeCost , bean.getUrl() );
							}
						}
					}
				}
			}
		}

	/**
	 * 格式化时间
	 *
	 * @param cnt
	 * @return
	 */
	private String getStringTime(long cnt) {
		long hour = cnt / 3600;
		long min = cnt % 3600 / 60;
		long second = cnt % 60;
		return String.format(Locale.CHINA, "%02d:%02d:%02d", hour, min, second);
	}


	/**
	 * 开始计时
	 */
	public void startClick() {
		timerTask = new TimerTask() {
			@Override
			public void run() {
				mActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mTimeTv.setText(getStringTime(cnt++));

					}
				});
			}
		};
		timer.schedule(timerTask, 0, 1000);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}
}
